package com.hy.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * cookie工具类
 * 
 *
 */
public class CookieUtils {
	private static Logger logger = LoggerFactory.getLogger(CookieUtils.class);
	/**
	 * 设置cookie
	 * @param response
	 * @param cookieName
	 * @param cookieValue
	 * @param expiry 多少秒后过期
	 */
	public static void setCookie(HttpServletResponse response,String cookieName,String cookieValue,int expiry){
		try{
			Cookie cidCookie=new Cookie(cookieName,cookieValue);
			cidCookie.setMaxAge(expiry);
			cidCookie.setPath("/");
			response.addCookie(cidCookie);
		}catch(Exception e){
			logger.error(getMethodPath()+".Exception:",e);
		}
	}
	/**
	 * 获得cookie
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookie(HttpServletRequest request,String cookieName){
		String result=null;
		try{
			Cookie[] cookies=request.getCookies();
			if(cookies!=null && cookies.length>0){
				for(Cookie c:cookies){
					if(c.getName().equals(cookieName)){
						result=c.getValue();
						break;
					}
				}
			}
		}catch(Exception e){
			result=null;
			logger.error(getMethodPath()+".Exception:",e);
		}
		return result;
	}
	/**
	 * 删除cookie
	 * @param response
	 * @param cookieName
	 */
	public static void removeCookie(HttpServletResponse response,String cookieName){
		try{
			Cookie cidCookie=new Cookie(cookieName,null);
			cidCookie.setMaxAge(0);
			cidCookie.setPath("/");
			response.addCookie(cidCookie);
		}catch(Exception e){
			logger.error(getMethodPath()+".Exception:",e);
		}
	}

	public static String getMethodPath() {
		String path = "";
		try {
			StackTraceElement[] st = new Exception().getStackTrace();
			if (st.length > 1) {
				path = st[1].getClassName().substring(
						st[1].getClassName().lastIndexOf(".") + 1)
						+ "." + st[1].getMethodName();
			}
		} catch (Exception e) {
			logger.error(getMethodPath()+".Exception :" + e) ;;
		}
		return path;
	}
}
